import Flutter
import UIKit

public class BatteryOptimizationsPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(
        name: "com.ashlikun.battery_opt",
        binaryMessenger: registrar.messenger()
    )
    let instance = BatteryOptimizationsPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "isInteractive":
        result(self.isScreenInteractive())
    default:
        result(FlutterMethodNotImplemented)
    }
  }

  // 核心判断逻辑
    private func isScreenInteractive() -> Bool {
      let screen = UIScreen.main

      // 1. 使用最新API名称
      let isUnlocked: Bool
      if #available(iOS 9.0, *) {
          isUnlocked = UIApplication.shared.isProtectedDataAvailable
      } else {
          // iOS 9.0以下设备默认为解锁状态
          isUnlocked = true
      }

      // 2. 亮度检测（兼容所有iOS版本）
      let isBright = screen.brightness > 0.01

      // 3. 屏幕镜像检测（iOS 11+）
      var isNotCaptured = true
      if #available(iOS 11.0, *) {
          isNotCaptured = !screen.isCaptured
      }

      // 4. 应用状态检测
      let isActive = UIApplication.shared.applicationState == .active

      return isBright && isUnlocked && isNotCaptured && isActive
    }
}
